<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>JSX中的事件绑定-this</title>
</head>
<body>
	<div id="root"></div>

  <!-- 添加依赖，三个包，使用 CDN 引入 -->
  <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <!-- babel -->
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

	<script type="text/babel">
		class App extends React.Component {
			constructor() {
				super()
				this.state = {
					meg: 'Hello World',
					counter: 30
				}

				this.onBtn1Click = this.onBtn1Click.bind(this)
			}

			onBtn1Click() {
				this.setState({
					counter: ++this.state.counter
				})
			}

			onBtn2Click = () => {
				// 这里的 this，是 class 作用域中的 this 指向的是当前创建出来的实例。
				this.setState({ counter: 1000 })
			}

			onBtn3Click() {
				this.setState({ counter: 9999 })
			}

			render() {
				const { counter } = this.state
				return (
					<div>
						<h2>{ counter }</h2>

						{/* this 绑定方式一：bind 绑定 */}
						<button onClick={ this.onBtn1Click }>按钮1</button>

						{/* this 绑定方式二：ES6 class fields */}
						<button onClick={ this.onBtn2Click }>按钮2</button>

						{/* this 绑定方式三：直接传入一个箭头函数 */}
						<button onClick={ () => this.onBtn3Click() }>按钮3</button>
					</div>
				)
			}
		}

		const root = ReactDOM.createRoot(document.querySelector('#root'))
		root.render(<App/>)
	</script>
</body>
</html>

